package main

import (
	"encoding/json"
	"fmt"
)

// mergeJSON 将两个JSON字符串合并并返回合并后的JSON字符串
func mergeJSON(jsonA, jsonB string) (string, error) {
	// 解析JSON字符串为map类型
	mapA := make(map[string]interface{})
	mapB := make(map[string]interface{})

	if err := json.Unmarshal([]byte(jsonA), &mapA); err != nil {
		return "", err
	}

	if err := json.Unmarshal([]byte(jsonB), &mapB); err != nil {
		return "", err
	}

	// 合并mapB到mapA
	for key, value := range mapB {
		mapA[key] = value
	}

	// 转换合并后的mapA为JSON字符串
	mergedJSON, err := json.Marshal(mapA)
	if err != nil {
		return "", err
	}

	// 手动释放mapB占用的内存
	mapB = nil

	return string(mergedJSON), nil
}

func main() {
	// 定义JSON字符串 A 和 B
	jsonA := `{"zhang": {"name": "zhang","age": 15},"li": {"name": "li","age": 15}}`
	jsonB := `{"zhang":{"name":"zhang","age":15},"zhao":{"name":"zhao","age":15}}`

	// 合并JSON字符串
	mergedJSON, err := mergeJSON(jsonA, jsonB)
	if err != nil {
		panic(err)
	}

	// 打印合并后的JSON字符串
	fmt.Println(mergedJSON)
}
